package com.ziyun.pop.mall.module.mall.web;

import com.service.common.constant.GoodsType;
import com.service.common.model.PageParamDto;
import com.service.goods.api.SearchService;
import com.service.goods.api.SellerService;
import com.service.goods.constant.GoodsResult;
import com.service.goods.exception.GoodsException;
import com.service.goods.model.category.CategoryBaseResultDto;
import com.service.goods.model.goods.BaseGoodsInfoVO;
import com.service.goods.model.search.GoodsCacheSearchResultDto;
import com.service.goods.model.search.GoodsSearchParamDto;
import com.service.goods.model.search.SellerCacheSearchResultDto;
import com.service.goods.model.search.SellerSearchParamDto;
import com.service.goods.model.seller.SellerInfoVO;
import com.service.model.quote.constant.AttributeType;
import com.service.model.quote.constant.OemCategoryType;
import com.service.quote.module.product.model.QuoteAttribute;
import com.service.quote.module.product.model.QuoteAttributeOption;
import com.service.quote.module.product.model.QuotePartsInfo;
import com.service.quote.module.product.model.QuoteProductInfo;
import com.service.utils.push.umeng.JsonResult;
import com.utility.JsonUtils;
import com.utility.New;
import com.ziyun.pop.mall.module.goods.service.PopGoodsService;
import com.ziyun.pop.mall.module.mall.service.MallIndexService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @author chenxiaoyi
 *
 *         MallPOP商城展示放行Controller
 */
@Api(value = "MallIndexController", tags = "报价商品展示Controller")
@Controller
public class MallIndexController {
	private static Logger _log = LoggerFactory.getLogger(MallIndexController.class);
	private static final String MODEL = "/mall";

	@Autowired
	private MallIndexService mallIndexService;

	@Autowired
	private PopGoodsService popGoodsService;

	@Autowired
	private SellerService sellerService;

	@Autowired
	private SearchService searchService;

	@ApiOperation(value = "POP商城首页")
	@GetMapping("/index.do")
	public ModelAndView mallIndex() {
		ModelAndView view = new ModelAndView("/mall/index/index.html");
		try {
			Map<Object, Object> allGoodsCategoryList = mallIndexService.getAllGoodsCategoryList();
			Map<Object, Object> allSellerInfo = mallIndexService.getAllSellerInfo(0, null);
			view.addObject("productMap", allGoodsCategoryList);// 报价热门产品分类
			view.addObject("sellerInfoMap", allSellerInfo);
		}catch (Exception e){
			view.addObject("productMap",new HashMap<>());
			view.addObject("sellerInfoMap",new HashMap<>());
		}

		return view;
	}


	/**
	 * 更多工厂
	 * 
	 */
	@ApiOperation(value = "优质供应商 更多页面")
	@GetMapping(MODEL + "/providerMore.do")
	public ModelAndView quoteFactoryMore() {
		ModelAndView view = new ModelAndView("/mall/more/provider/index.html");
		Map<Object, Object> allSellerInfo = mallIndexService.getAllSellerInfo(1, null);
		view.addObject("sellerInfoMap", allSellerInfo);
		return view;
	}

	/**
	 * 更多工厂 获取分页数据
	 * 
	 */
	@ApiOperation(value = "更多页面的分页数据")
	@PostMapping(MODEL + "/pageProviderMore.do")
	@ResponseBody
	public Map<Object, Object> pageFactoryMore(String pageParamDto) {
		PageParamDto pageParam = JsonUtils.string2Object(pageParamDto, PageParamDto.class);
		return mallIndexService.getAllSellerInfo(1, pageParam);
	}

	/**
	 * 查看工厂的详情
	 */
	@ApiOperation(value = "工厂详情和关联的商品")
	@GetMapping(MODEL + "/providerDetail.do")
	public ModelAndView quoteFactoryDetail(String sellerId) {
		
		try {
			ModelAndView view = new ModelAndView("/mall/provider/providerDetails.html");
			// 工厂关联商品
			Map<Object, Object> allSellerGoodsCategoryList = mallIndexService.quoteFactoryDetail(Long.valueOf(sellerId));
			view.addObject("productList", allSellerGoodsCategoryList);
			// 工厂详情
			SellerInfoVO sellerInfoVO = sellerService.getSellerDetails(Long.valueOf(sellerId), null, null, null, null).getData();
			view.addObject("sellerInfoVO", sellerInfoVO);
			return view;
		} catch (GoodsException oe) {
			System.out.println(oe.getResultCode().getMessage());
			ModelAndView view = new ModelAndView("/error/error.html");
			view.addObject("errorMessage", oe.getResultCode().getMessage());
			return view;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		return null;
	}

	/**
	 * 商品搜索 页面
	 */
	@GetMapping(MODEL + "/goodsSearch.html")
	public ModelAndView goodsSearch(String keyword) {
		ModelAndView view = new ModelAndView("/mall/search/productSearch.html");
		view.addObject("keywords", keyword);
		return view;
	}

	/**
	 * 工厂搜索
	 */
	@GetMapping(MODEL + "/providerSearch.html")
	public ModelAndView providerSearch(String keyword) {
		ModelAndView view = new ModelAndView("/mall/search/providerSearch.html");
		view.addObject("keywords", keyword);
		return view;
	}

	/**
	 * 商品搜索
	 * 
	 * @param goodsSearchParamDto
	 *            搜索参数
	 */
	@PostMapping(MODEL + "/searchGoods.json")
	@ResponseBody
	public GoodsResult<GoodsCacheSearchResultDto> searchGoods(String goodsSearchParamDto) {
		GoodsSearchParamDto dto = JsonUtils.string2Object(goodsSearchParamDto, GoodsSearchParamDto.class);
		dto.setPageSize(20);
		return searchService.searchGoodsList(dto);
	}

	/**
	 * 供应商搜索
	 * 
	 * @param merchantSearchParamDto
	 *            搜索参数
	 */
	@PostMapping(MODEL + "/searchProvider.json")
	@ResponseBody
	public GoodsResult<SellerCacheSearchResultDto> searchProvider(String merchantSearchParamDto) {
		SellerSearchParamDto dto = JsonUtils.string2Object(merchantSearchParamDto, SellerSearchParamDto.class);
		dto.setSellerType("1");
		return searchService.searchMerchant(dto);
	}

	@ApiOperation(value = "商品列表 json数据")
	@PostMapping(MODEL + "/productList.json")
	@ResponseBody
	public GoodsResult<GoodsCacheSearchResultDto> getProeuctList(String categoryId) {
		return mallIndexService.queryGoodsByCategoryId(categoryId);
	}

	/**
	 * 更多热门商品和品质耗材
	 * 
	 */
	@ApiOperation(value = "热门商品和品质耗材 更多页面")
	@GetMapping(MODEL + "/productMore.do")
	public ModelAndView quoteProductMore() {
		ModelAndView view = new ModelAndView("/mall/more/product/index.html");
		Map<Object, Object> map = mallIndexService.queryGoodscategory();
		view.addObject("productMap", map);
		return view;
	}

	/**
	 * 热门商品和品质耗材三级分类 json数据
	 * 
	 * @param categoryId
	 * @return
	 */
	@ApiOperation(value = "热门商品和品质耗材 json数据")
	@PostMapping(MODEL + "/getProductMore.json")
	@ResponseBody
	public JsonResult<List> getProeuctMore(Integer categoryId) {
		List<CategoryBaseResultDto> categoryLeavel3 = mallIndexService.getCategoryLeavel3(categoryId);
		return JsonResult.success(categoryLeavel3);
	}

	/**
	 * 单个分类点击进来 判断到spu列表还是报价详情
	 * 
	 * @return
	 */
	@ApiOperation(value = "三级分类点击分发页面")
	@GetMapping(MODEL + "/category.do")
	public ModelAndView clickCategory(Integer categoryId, OemCategoryType type) {
		ModelAndView view = new ModelAndView();
		// 分类分发 报价品 标品
		if (null == type) {
			view.setViewName("/mall/product/productList.html");// 去标品列表页面
			view.addObject("categoryId", categoryId);
		} else {
			view.setViewName("/mall/product/skuQuote.html");// 去报价页面，加找工厂
			try {
				QuoteProductInfo quoteProductInfo = mallIndexService.queryQuoteGoodsByCategoryId(categoryId);
				Map<String, Object> optionAttr = optionAttr(quoteProductInfo);

				List<QuotePartsInfo> partsList = quoteProductInfo.getQuotePartsList();
				Map<Integer, List<QuoteAttributeOption>> map = New.hashMap();

				for (QuotePartsInfo quotePartsInfo : partsList) {
					List<QuoteAttributeOption> quoteOption = New.arrayList();
					for (QuoteAttribute quoteAttribute : quotePartsInfo.getQuoteAttributeList()) {
						if (AttributeType.material.equals(quoteAttribute.getAttributeType())) {
							List<QuoteAttributeOption> optionList = quoteAttribute.getQuoteAttributeOptionList();
							for (QuoteAttributeOption option : optionList) {
								quoteOption.addAll((option.getSonOptionList()));
							}
						}
					}
					map.put(quotePartsInfo.getConstructId(), quoteOption);
				}
				view.addObject("code",0);
				view.addObject("quoteProductInfo", quoteProductInfo);
				view.addObject("materialMap", map);
				view.addObject("outAttrJ", optionAttr.get("outAttrJ").toString());// 互斥
				view.addObject("outOptJ", optionAttr.get("outOptJ").toString());// 互斥
			}catch (Exception e){
				_log.error("quoteProductService.getProductInfo error");
				view.addObject("code",999);
				view.addObject("quoteProductInfo", new QuoteProductInfo());
				view.addObject("materialMap", new HashMap<Integer, List<QuoteAttributeOption>>());
				view.addObject("outAttrJ", JsonUtils.map2String(new HashMap<>()));// 互斥
				view.addObject("outOptJ",JsonUtils.map2String(new HashMap<>()));// 互斥
			}
		}
		return view;
	}

	@ApiOperation(value = "spu到详情页 分发报价商品和标准商品")
	@GetMapping(MODEL + "/skuProductDetails.do")
	public ModelAndView toStandradProduct(Long goodsId, GoodsType goodsType) {
		ModelAndView view = new ModelAndView();
		// spu进入报价品或者标品
		if (GoodsType.paper.equals(goodsType) || GoodsType.standard.equals(goodsType)
				|| GoodsType.copy.equals(goodsType) || GoodsType.design.equals(goodsType)||GoodsType.material.equals(goodsType)) {
			view.setViewName("/mall/product/standradProduct.html");// spu标品详情页
		} else {
			view.setViewName("/mall/product/spuQuoteDetails.html");// spu报价详情页
		}
		view.addObject("goodsId", goodsId);
		view.addObject("goodsType", goodsType);

		return view;
	}

	/**
	 * 标品大纸设计商品复印纸页面的首次参数数据
	 * 
	 * @return
	 */
	@PostMapping(MODEL + "/standradDetails.json")
	@ResponseBody
	public GoodsResult<BaseGoodsInfoVO> standradDetails(Long goodsId) {
		return popGoodsService.getGoodsInfo(goodsId);
	}

	// 组装报价页面互斥属性

	private Map<String, Object> optionAttr(QuoteProductInfo quoteProductInfo) {
		Map<String, Object> rejectMap = New.hashMap();
		Map<String, Object> outAttr = new HashMap<>(); // 属性排他
		Map<String, Object> outOpt = new HashMap<>(); // 选项排他
		List<QuotePartsInfo> quotePartsList = quoteProductInfo.getQuotePartsList();
		for (QuotePartsInfo quotePartsInfo : quotePartsList) {
			Integer id = quotePartsInfo.getConstructId();
			HashSet<Map<String, Integer[]>> optionAttributeOutIds = quotePartsInfo.getOptionAttributeOutIds();
			HashSet<TreeSet<Integer>> optionOptionOutIds = quotePartsInfo.getOptionOptionOutIds();
			if (optionAttributeOutIds == null) { // 如果optionAttributeOutIds 没有参数则存一个空数组
				outAttr.put(String.valueOf(id), new Integer[0]);
			} else { // 如果有参数就传入对象+数组的形式
				Map<String, Integer[]> map = new HashMap<>();
				for (Map<String, Integer[]> treeSet : optionAttributeOutIds) {
					Set<Map.Entry<String, Integer[]>> entrySet = treeSet.entrySet();
					for (Map.Entry<String, Integer[]> entry : entrySet) {
						map.put(entry.getKey(), entry.getValue());
					}
				}
				outAttr.put(String.valueOf(id), map);
			}
			outOpt.put(String.valueOf(id), optionOptionOutIds);
		}
		net.sf.json.JSONObject outAttrJ = net.sf.json.JSONObject.fromObject(outAttr);
		net.sf.json.JSONObject outOptJ = net.sf.json.JSONObject.fromObject(outOpt);
		rejectMap.put("outAttrJ", outAttrJ);
		rejectMap.put("outOptJ", outOptJ);

		return rejectMap;
	}

}
